package com.pingan.haofang.searchcloud.index.rpc;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pingan.haofang.searchcloud.common.redis.RedisQueueListener;
import com.pingan.haofang.searchcloud.common.redis.RedisQueueManager;
import com.pingan.haofang.searchcloud.common.rpc.RPCExporter;
import com.pingan.haofang.searchcloud.index.constants.IndexBuildConstants;
import com.pingan.haofang.searchcloud.index.dto.IndexBuildIncDTO;
import com.pingan.haofang.searchcloud.index.service.IndexBuildService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 索引构建RPC
 *
 * @author LUYI374
 * @date 2017年5月11日
 * @since 1.0.0
 */
@Component
public class IndexBuildRPCService {

    Logger LOGGER = LoggerFactory.getLogger(IndexBuildRPCService.class);

    @Autowired
    private IndexBuildService indexBuildService;

    @Autowired
    private ThreadPoolExecutor incConsumerThreadCPool;

    @Autowired
    private RedisQueueListener redisQueueListener;

    @Resource(name = "redisQueueTemplate")
    private RedisTemplate redisTemplate;

    @Value("${indexBuild.incMsgConsumeRate:500}")
    private int rate ;

    private Gson GSON = new GsonBuilder().serializeNulls().setLenient().create();

    private final String INC_MSG_KEY_TEMP = "%s:%s";
    /**
     * 每次消息处理个数
     */
    @Value("${indexBuild.incMsgBatchSize:10}")
    private int batchSize = 10;

    /**
     *
     *锁过期时间ms
     */
    @Value("${indexBuild.incMsgExpireTime:1000}")
    private int expireTime = 1000;

    /**
     * 发送增量索引构建消息
     *
     * @param dto
     */
    @RPCExporter("buildIndex")
    public void buildIndex(IndexBuildIncDTO dto) {
        if (dto == null ||
                ((dto.getContent() == null || dto.getContent().size() == 0) && (dto.getIdList() == null || dto.getIdList().size() == 0))) {
            LOGGER.info("invalid inc-index-msg:{}", dto);
            return;
        }
        //消息进入队列
        RedisQueueManager.getInstanceOf(redisTemplate).pushMsg(this.getIncRedisKey(dto), GSON.toJson(dto));
        LOGGER.info("inc msg pushed, key:{}, msg:{}", this.getIncRedisKey(dto), dto);
    }

    private String getIncRedisKey(IndexBuildIncDTO dto) {
        return String.format(INC_MSG_KEY_TEMP, IndexBuildConstants.INDEX_INC_KEY_PERFIX, indexBuildService.getKey(dto.getProjectCode(), dto.getIndexName()));
    }


}
